package com.lvhr.rpc.utils;

import com.lvhr.rpc.model.RpcRequest;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 签名认证工具类
 */
public class SignatureUtils {
    public static String buildSignContent(RpcRequest request) {
        return request.getAttachments().entrySet().stream()
                .filter(e -> !"X-Signature".equals(e.getKey()))
                .sorted(Map.Entry.comparingByKey())
                .map(e -> e.getKey() + "=" + e.getValue())
                .collect(Collectors.joining("&"));
    }



    public static String hmacSha256(String key, String data) throws Exception {
        // 强制使用UTF-8编码并去除不可见字符
        Charset charset = StandardCharsets.UTF_8;
        String normalized = data.replaceAll("\\p{C}", "").trim();

        SecretKeySpec secretKey = new SecretKeySpec(
                key.getBytes(charset),
                "HmacSHA256");

        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(secretKey);
        return Hex.encodeHexString(mac.doFinal(normalized.getBytes(charset)));
    }




}
